#!/usr/bin/env python
# -*- coding: utf-8 -*-

import csv
import sys
import os
reload(sys)
sys.setdefaultencoding('utf-8')


def colorPrint(color, print_string):
    color_dict = {
        'blue': '34',
        'red': '31',
        'green': '32',
        'yellow': '33',
        'pink': '35',
        'light-blue': '36'
    }
    if color in color_dict:
        print('\033[1;%sm%s\033[0m' % (color_dict[color], print_string))
    elif color in color_dict.values():
        print('\033[1;%sm%s\033[0m' % (color, print_string))
    else:
        print('颜色不支持')


def checkStatus(status, warning_string):
    if status != 0:
        colorPrint('red', warning_string)
        sys.exit(1)


def osExcute(cmd, warning_string):
    try:
        status = os.system(cmd)
        checkStatus(status, warning_string)
    except Exception, e:
        colorPrint('red', e)
        sys.exit(1)


# 解析csv文件，格式为：ip1,ip2,ip3,passwd,机房(腾讯云),平台,用途
role_info_file = '/data/fabfile/rolesmirh5.csv'
importres_file_path = '/data/fabfile'
tmp_csv_file_path = '/data/fabfile/csvdir'
all_host_list = []
try:
    with open(role_info_file, 'rw') as f:
        reader = csv.reader(f)
        for line in reader:
            all_host_list.append(line)
        if len(all_host_list) == 0:
            colorPrint('red', '%s 文件为空' % role_info_file)
            sys.exit(1)
except Exception, e:
    colorPrint('red', e)
    sys.exit(1)

# 生成导入资源中心的列表文件
use_dict = {
    'game': '游戏服',
    'admin': '管理后台',
    'center': '中心机',
    'other': '其他',
    'gamebackup': '游戏服预留',
    'kuafu': '跨服战',
    'pay': '充值',
    'login': '登录'
}
role_info_dict = {}
for info in all_host_list:
    if info[-1] not in use_dict.keys():
        colorPrint('red', '%s 并不是指定的用途' % info[-1])
        sys.exit(1)
    else:
        if info[-1] in role_info_dict:
            role_info_dict[info[-1]].append(info[0:-1])
        else:
            role_info_dict[info[-1]] = [info[0:-1]]

for machine_type in role_info_dict.keys():
    with open('%s/role%s.csv' % (tmp_csv_file_path, machine_type), 'w') as f:
        csv_writer = csv.writer(f)
        for a in role_info_dict[machine_type]:
            csv_writer.writerow(a)

# 打印初始化的机器列表，进行确认
colorPrint('green', '开始初始化以下主机：')
for i in all_host_list:
    print('%s' % ','.join(i))

choice = raw_input('请问是否开始初始化(y/n):').strip().upper()
if choice == 'N':
    colorPrint('red', '取消初始化,退出程序')
    sys.exit(1)
elif choice == 'Y':
    pass
else:
    colorPrint('red', '%s 是无效的选项,退出程序' % choice)
    sys.exit(1)

# 开始分区
colorPrint('green', '==================开始分区====================')
osExcute('cd %s/fdisk;python batch-mkfs.py' % importres_file_path, '格式化失败')

# 开始导入资源中心
colorPrint('green', '=============开始导入资源中心===================')
for use in role_info_dict.keys():
    cmd = 'cd /data/script;python ImportResource.py -f %s/role%s.csv -t %s' % (
        tmp_csv_file_path, use, use)
    osExcute(cmd, '%s 中有机器导入资源中心出错' % use)

# 开始初始化环境
colorPrint('green', '=============开始初始化环境===================')
osExcute('cd %s;fab -f fabmirh5.py main' % importres_file_path, 'lnmp安装失败')

colorPrint('green', '机器初始化完成')
